import React, { useContext, FC, useState, useEffect } from 'react';
import { Tabs } from 'antd';
import { DragDropContext } from 'react-beautiful-dnd';
import { uuid } from '@/utils';
import { DesignRedux } from '../DesignRedux';

import CenterDesign from '../CenterDesign';
import LevelTree from '../LevelTree';
import RightForm from '../RightForm';
import LeftBtn from '../LeftBtn';
import styles from './index.less';
import { comObj, mockSchema } from './mock';

const { TabPane } = Tabs;

const DesignIndex: FC = () => {
  const [dragStartStatus, setDragStartStatus] = useState(false);
  const [tabKey, setTabKey] = useState('1');
  const { globalState, dispatch } = useContext(DesignRedux);

  const { schema } = globalState;

  useEffect(() => {
    dispatch({ schema: mockSchema });
  }, []);

  // 拖动结束
  const onDragEnd = (result: any) => {
    // dropped outside the list
    if (!result.destination) {
      return;
    }

    const { source, destination, draggableId } = result;
    const { droppableId: sId, index: sIndex } = source;
    const { droppableId: dId, index: dIndex } = destination;

    const tempSchema = [...schema];

    // todo
    if (sId == 'qhDesignLeft' && dId == 'qhDesignCenter') {
      // 添加默认
      let temp = comObj[draggableId];
      temp.id = uuid();
      tempSchema.push(JSON.parse(JSON.stringify(temp)));
    }

    // 判断是否在同一个容器中
    if (source.droppableId === destination.droppableId) {
      // 内容交换
      [tempSchema[dIndex], tempSchema[sIndex]] = [
        tempSchema[sIndex],
        tempSchema[dIndex],
      ];
    }

    dispatch({ schema: tempSchema });
    setDragStartStatus(false);
  };

  // 开始拖拽
  const onDragStart = () => {
    setDragStartStatus(true);
  };

  // 左侧tab 切换
  const callbackTab = (key: string) => {
    setTabKey(key);
  };

  return (
    <DragDropContext onDragEnd={onDragEnd} onDragStart={onDragStart}>
      <div className={styles.beautifulContent}>
        {/*左侧元素*/}
        <div className={styles.qhDesignLeft}>
          <Tabs activeKey={tabKey} onChange={callbackTab}>
            <TabPane tab="组件" key="1" />
            <TabPane tab="层级" key="2" />
          </Tabs>

          {/*组件*/}
          {tabKey == '1' && <LeftBtn droppableId="qhDesignLeft" />}

          {/*层级*/}
          {tabKey == '2' && !dragStartStatus && <LevelTree schema={schema} />}
        </div>

        {/*设计*/}
        <div className={styles.qhDesignCenter}>
          <CenterDesign schema={schema} droppableId="qhDesignCenter" />
        </div>

        {/*属性*/}
        <div className={styles.qhDesignRight}>
          <RightForm />
        </div>
      </div>
    </DragDropContext>
  );
};

export default DesignIndex;
